package com.zahb.qadx.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.view.CornerImageView;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.GlideImageLoader;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


public class StudentCardActivity extends BaseActivity {

    int classid;
    @BindView(R.id.iv)
    CornerImageView iv;
    @BindView(R.id.ivAddOne)
    ImageView ivAddOne;
    @BindView(R.id.llAdd)
    LinearLayout llAdd;
    @BindView(R.id.tvComment)
    TextView tvComment;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvContent)
    TextView tvContent;

    @Override
    protected int getLayout() {
        return R.layout.activity_student_card;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        classid = getIntent().getIntExtra("id", 0);

        llAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureSelector.create(StudentCardActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .imageEngine(GlideImageLoader.createGlideEngine())
                        .isEnableCrop(true)
                        .cropImageWideHigh(295,413)
                        .isCompress(true)
                        .compressQuality(40) // 图片压缩后输出质量
                        .maxSelectNum(1)
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(StudentCardActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .imageEngine(GlideImageLoader.createGlideEngine())
                        .isEnableCrop(true)
                        .cropImageWideHigh(295,413)
                        .isCompress(true)
                        .compressQuality(40) // 图片压缩后输出质量
                        .maxSelectNum(1)
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });

        getClassStudentCartInfo();
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.student_card;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> images =
                        PictureSelector.obtainMultipleResult(data);
                if (images.size() > 0) {
                    String path = GlideImageLoader.getPath(images.get(0));
                    upload(path);

                }
            }

        }
    }



    public void getClassStudentCartInfo(){

        addDisposable(RetrofitService.getNetService()
                .getClassStudentCartInfo(classid, BaseApplication.getContext().getDataLogin().getUser().getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {

                        tvName.setText(response.getData().getUserName());
                        tvContent.setText("企业名称："+response.getData().getRootOrgName()
                                +"\n岗位名称："+response.getData().getPost()
                                +"\n培训班级："+response.getData().getClassName()
                                +"\n有效期限："+response.getData().getStartTime()
                                +" ～ "+response.getData().getEndTime());

                        if(TextUtils.isEmpty(response.getData().getOneInchPhoto())){
                            iv.setVisibility(View.GONE);
                            llAdd.setVisibility(View.VISIBLE);

                            tvComment.setVisibility(View.VISIBLE);
                        }else{
                            iv.setVisibility(View.VISIBLE);
                            llAdd.setVisibility(View.GONE);
                            tvComment.setVisibility(View.GONE);
                            ImageLoaderKt.loadImage(iv,response.getData().getOneInchPhoto());
                        }

                    }
                }, throwable -> {
                    Tips.RequestError(getActivity());
                    throwable.printStackTrace();
                }));

    }

    public String imgUrl = "";
    public void upload(String path) {
        if (TextUtils.isEmpty(path)) {
            Log.v("zzw", "路径为空");
            return;
        }
        File imgFile = new File(path);
        if (!imgFile.exists() || !imgFile.isFile()) {
            Log.v("zzw", "文件不存在");
            return;
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), imgFile);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", imgFile.getName(), requestBody);
        addDisposable(RetrofitService.getNetService()
                .upload(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        imgUrl=response.getData();
                        UpdateOneInchPhoto(imgUrl);
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }
    public void UpdateOneInchPhoto(String path) {

        addDisposable(RetrofitService.getNetService()
                .UpdateOneInchPhoto(BaseApplication.getContext().getDataLogin().getUser().getId(),path)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        getClassStudentCartInfo();
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

}
